package zuo.algo.c03;

import zuo.algo.util.SortUtils;

import java.util.Arrays;

/**
 * 01:28-逆序对问题-归并排序扩展
 * 在一个数组中，左边的数如果比右边的数大，则这两个数构成一个逆序对
 * 请打印所有这样的逆序对
 */
public class ReverseNum {

    public static int reverse1(int[] arr) {
        if (arr == null || arr.length < 2) {
            return 0;
        }
        int res = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    res++;
                }
            }
        }
        return res;
    }

    public static int reverse2(int[] arr) {
        if (arr == null || arr.length < 2) {
            return 0;
        }
        return process(arr, 0, arr.length - 1);
    }

    private static int process(int[] arr, int begin, int end) {
        if (end <= begin) {
            return 0;
        }
        int mid = begin + (end - begin) / 2;
        return process(arr, begin, mid) + process(arr, mid + 1, end) + merge(arr, begin, mid, end);
    }

    private static int merge(int[] arr, int begin, int mid, int end) {
        int res = 0;
        int idx = 0, idx1 = begin, idx2 = mid + 1;
        int[] tempArr = new int[end - begin + 1];
        while (idx1 <= mid && idx2 <= end) {
            if (arr[idx1] <= arr[idx2]) {
                tempArr[idx++] = arr[idx1++];
            } else {
                res += (mid - idx1 + 1);
                tempArr[idx++] = arr[idx2++];
            }
        }
        while (idx1 <= mid) {
            tempArr[idx++] = arr[idx1++];
        }
        while (idx2 <= end) {
            tempArr[idx++] = arr[idx2++];
        }
        for (idx = 0, idx1 = begin; idx < tempArr.length; idx++) {
            arr[idx1++] = tempArr[idx];
        }
        return res;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 1000000; i++) {
            int[] arr1 = SortUtils.getRandomArr(1000, 10000);
            int[] arr2 = Arrays.copyOf(arr1, arr1.length);
            int res1 = reverse1(arr1);
            int res2 = reverse2(arr2);
            if (res1 != res2) {
                throw new RuntimeException();
            }
            System.out.println(i);
        }
    }
}